<template>
  <div class="app-container">

    <!-- 顶部查询表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="100px" style="margin-bottom: 8px;">
      <el-form-item label="支付日期" prop="payTime">
        <el-date-picker v-model="payTime" type="daterange" range-separator="-" start-placeholder="支付日期" end-placeholder="支付日期" value-format="yyyy-MM-dd" style="width: 220px;" />
      </el-form-item>
      <el-form-item label="店铺名称" prop="shopName">
        <el-select v-model="queryParams.shopName" placeholder="请选择店铺" clearable style="width: 160px;">
          <el-option v-for="item in shopList" :key="item.id" :label="item.shopName" :value="item.id" /> 
        </el-select>
      </el-form-item>
      <el-form-item label="会员名称" prop="clientName">
        <el-input v-model="queryParams.clientName" placeholder="请输入会员名称" clearable style="width: 160px;" />
      </el-form-item>
      <el-form-item label="发货单号" prop="shipmentCode">
        <el-input v-model="queryParams.shipmentCode" placeholder="请输入发货单号" clearable style="width: 160px;" />
      </el-form-item>
      <el-form-item label="平台单号" prop="platformOrderCode">
        <el-input v-model="queryParams.platformOrderCode" placeholder="请输入平台单号" clearable style="width: 160px;" />
      </el-form-item>
      <el-form-item label="订单编号">
        <el-input v-model="queryParams.orderCode" placeholder="请输入订单编号" clearable style="width: 160px;" />
      </el-form-item>
      <el-form-item label="订单状态" prop="orderStatus">
        <el-select v-model="queryParams.orderStatus" placeholder="请选择订单状态" clearable style="width: 140px;">
         <el-option
            v-for="dict in dict.type.order_progress"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="发货单作废">
        <el-checkbox v-model="cancelled" />
      </el-form-item>
      <el-form-item label="是否拦截">
        <el-checkbox v-model="intercepted" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" style="background:#FF5000;border-color:#FF5000;" size="small" @click="handleQuery">搜索</el-button>
        <el-button size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 功能按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" size="mini" @click="handleAuditPass">财审通过</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" size="mini" @click="handleAuditReject">财审驳回</el-button>
      </el-col>
    </el-row>

     <!-- 表格信息、分页 -->
    <div class="app-container-main">
      <vxe-table border stripe v-loading="loading" ref="mainTable" size="small" header-align="center"
        :data="mainTableData" @checkbox-change="mainCheckboxChange" @checkbox-all="mainCheckboxAll"
        @cell-click="cellClickEvent" scroll-x="auto"
        :row-config="rowConfig"
        :column-config="columnConfig"
      >
        <vxe-column type="checkbox" width="60" fixed="left"></vxe-column>
        <vxe-column type="seq" title="序号" width="60" fixed="left"></vxe-column>
        <vxe-column field="shipmentCode" title="发货单号" width="140" fixed="left" align="center"></vxe-column>
        <vxe-column field="shopName" title="店铺" width="120" align="center"></vxe-column>
        <vxe-column field="platformOrderCode" title="平台单号" width="140" align="center"></vxe-column>
        <vxe-column field="orderAmount" title="订单金额" width="100" align="center"></vxe-column>
        <vxe-column field="refundFlag" title="退款" width="80" align="center"></vxe-column>
        <vxe-column field="clientName" title="会员名称" width="120" align="center"></vxe-column>
        <vxe-column field="warehouseName" title="仓库" width="120" align="center"></vxe-column>
        <vxe-column field="expressCompany" title="物流公司" width="120" align="center"></vxe-column>
        <vxe-column field="orderCount" title="商品数量" width="100" align="center"></vxe-column>
        <vxe-column field="buyerRemark" title="买家留言" width="140" align="center" show-overflow></vxe-column>
        <vxe-column field="sellerRemark" title="卖家备注" width="140" align="center" show-overflow></vxe-column>
        <vxe-column field="secondRemark" title="二次备注" width="140" align="center" show-overflow></vxe-column>
        <vxe-column field="extraInfo" title="附加信息" width="140" align="center" show-overflow></vxe-column>
        <vxe-column field="payTime" title="支付时间" width="140" align="center"></vxe-column>
        <vxe-column field="prepareTime" title="配货时间" width="140" align="center"></vxe-column>
        <vxe-column field="prepareUser" title="配货人" width="100" align="center"></vxe-column>
        <vxe-column field="codFlag" title="货到付款" width="100" align="center"></vxe-column>
        <vxe-column field="interceptFlag" title="拦截" width="80" align="center"></vxe-column>
        <vxe-column field="cancelFlag" title="作废" width="80" align="center"></vxe-column>
      </vxe-table>

      <!-- 主表格分页 -->
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </div>

    <!-- 底部Tab区域 -->
    <div class="app-container-footer">
      <el-tabs v-model="activeTab" type="border-card">
        <el-tab-pane label="销售订单明细" name="saleDetails">
          <SaleDetails :deliveryOrderId="currentCellId" />
        </el-tab-pane>
        <el-tab-pane label="商品明细" name="itemDetail">
          <ItemDetail :deliveryOrderId="currentCellId" />
        </el-tab-pane>
        <el-tab-pane label="收货信息" name="shippingInfo">
          <ShippingInfo :deliveryOrderId="currentCellId" />
        </el-tab-pane>
        <el-tab-pane label="操作日志" name="opLog">
          <OpLog :deliveryOrderId="currentCellId" />
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 拆分弹窗 -->
    <el-dialog :visible.sync="splitDialog.visible" title="拆单" width="400px" @close="closeSplitDialog">
      <div v-if="splitDialog.data">
        <p>当前配货单号：{{ splitDialog.data.prepareCode }}</p>
        <el-form label-width="100px">
          <el-form-item label="拆分数量">
            <el-input v-model="splitDialog.splitQty" placeholder="请输入拆分数量" type="number" min="1" />
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSplitSubmit">确 定</el-button>
        <el-button @click="closeSplitDialog">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 手工配货弹窗 -->
    <el-dialog :visible.sync="manualDialog.visible" title="手工配货" width="700px" @close="closeManualDialog">
      <vxe-table border stripe size="small" header-align="center" :data="manualDialog.detailList" ref="manualTable"
        :checkbox-config="{ range: true }" @checkbox-change="onManualCheckChange">
        <vxe-column type="checkbox" width="60"></vxe-column>
        <vxe-column field="itemName" title="商品名称" align="center"></vxe-column>
        <vxe-column field="specName" title="规格" align="center"></vxe-column>
        <vxe-column field="qty" title="可配数量" align="center"></vxe-column>
      </vxe-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleManualDelivery">确 定</el-button>
        <el-button @click="closeManualDialog">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 批量操作弹窗 -->
    <el-dialog :visible.sync="batchDialog.visible"
      :title="batchDialog.type === 'warehouse' ? '批量修改仓库' : batchDialog.type === 'express' ? '批量修改物流公司' : '批量转为现货订单'" width="400px"
      @close="handleBatchCancel">
      <el-form v-if="batchDialog.type === 'warehouse'" label-width="100px">
        <el-form-item label="新仓库名称">
          <el-input v-model="batchForm.warehouseName" placeholder="请输入新仓库名称" />
        </el-form-item>
      </el-form>
      <el-form v-if="batchDialog.type === 'express'" label-width="100px">
        <el-form-item label="新物流公司">
          <el-input v-model="batchForm.expressCompany" placeholder="请输入新物流公司" />
        </el-form-item>
      </el-form>
      <div v-if="batchDialog.type === 'stock'" style="padding: 20px 0; text-align: center;">确定将选中配货单转为现货订单？</div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleBatchSubmit">确 定</el-button>
        <el-button @click="handleBatchCancel">取 消</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import ItemDetail from './components/itemDetail.vue';
import OpLog from './components/opLog.vue';
import ShippingInfo from './components/shippingInfo.vue';
import SaleDetails from './components/saleDetails.vue'
import { listShopBasic } from "@/api/mes/sales/shopBasic";

import {
  listFinancialAudit,
  auditPassFinancial,
  auditRejectFinancial
} from "@/api/mes/sales/financialAudit";


export default {
  name: "FinancialAudit",
  dicts: ['order_progress'],
  components: {
    SaleDetails,
    ItemDetail,
    OpLog,
    ShippingInfo
  },
  data() {
    return {
      loading: true,
      ids: [],
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        shopName: undefined,
        clientName: undefined,
        shipmentCode: undefined,
        platformOrderCode: undefined,
        orderStatus: undefined,
      },
      mainTableData: [],
      activeTab: 'saleDetails',
      payTime: this.getDefaultDateRange(),
      currentCellId: null,
      // 添加缺失的对话框数据
      splitDialog: {
        visible: false,
        data: null,
        splitQty: 1
      },
      manualDialog: {
        visible: false,
        detailList: [],
        selected: []
      },
      batchDialog: {
        visible: false,
        type: ''
      },
      batchForm: {
        warehouseName: '',
        expressCompany: ''
      },
      cancelled: false,
      intercepted: false,
      shopList: [],
      columnConfig: {
        drag: true,
        resizable: true,
        storage: true,
        sortConfig: {
          trigger: 'cell',
          remote: true
        },
        align: 'center',
        headerAlign: 'center'
      },
      rowConfig: {
        drag: true,
        keyField: 'id',
        isHover: true,
        isCurrent: true,
      },
    };
  },
  created() {
    this.getList();
    this.getShopList()
  },
  methods: {
    getDefaultDateRange() {
      const today = new Date();
      const thirtyDaysAgo = new Date();
      thirtyDaysAgo.setDate(today.getDate() - 30);
      const formatDate = (date) => {
          const year = date.getFullYear();
          const month = String(date.getMonth() + 1).padStart(2, '0');
          const day = String(date.getDate()).padStart(2, '0');
          return `${year}-${month}-${day}`;
      };
      return [formatDate(thirtyDaysAgo), formatDate(today)];
    },
    // 店铺下拉数据
    getShopList(){
      listShopBasic({
        enabled: 1,
        pageNum: 1,
        pageSize: 9999
      }).then(response => {
        this.shopList = response.rows;
      })
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      this.queryParams.cancelled = this.cancelled ? '1' : '0';
      this.queryParams.intercepted = this.intercepted ? '1' : '0';
      if (this.payTime && this.payTime.length === 2) {
        this.queryParams.payStartDate = this.payTime[0];
        this.queryParams.payEndDate = this.payTime[1];
      } else {
        this.queryParams.payStartDate = undefined;
        this.queryParams.payEndDate = undefined;
      }
      listFinancialAudit(this.queryParams)
        .then(response => {
          this.mainTableData = response.rows || [];
          this.total = response.total || 0;
          if (this.mainTableData.length > 0) {
            // this.currentCellId = this.mainTableData[0].id;
            this.$refs.mainTable.setCurrentRow(this.mainTableData[0]);
            this.cellClickEvent({ row: this.mainTableData[0] });
          }
        })
        .catch(error => {
          console.error("获取列表数据失败:", error);
          this.$modal.msgError("获取数据失败");
        })
        .finally(() => {
          this.loading = false;
        });
    },
    handleAuditPass() {
      if (!this.ids || this.ids.length === 0) {
        this.$modal.msgError('请选择要操作的数据');
        return;
      }
      this.$confirm('确定对选中的订单进行财审通过吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.loading = true;
        auditPassFinancial({ shipmentIds: this.ids })
          .then(() => {
            this.$modal.msgSuccess('财审通过成功');
            this.getList();
          })
          .catch(() => {
            this.$modal.msgError('财审通过失败');
          })
          .finally(() => {
            this.loading = false;
          });
      });
    },
    handleAuditReject() {
      if (!this.ids || this.ids.length === 0) {
        this.$modal.msgError('请选择要操作的数据');
        return;
      }
      this.$confirm('确定对选中的订单进行财审驳回吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.loading = true;
        auditRejectFinancial({ shipmentIds: this.ids })
          .then(() => {
            this.$modal.msgSuccess('财审驳回成功');
            this.getList();
          })
          .catch(() => {
            this.$modal.msgError('财审驳回失败');
          })
          .finally(() => {
            this.loading = false;
          });
      });
    },
    handleManualDelivery() {
      if (!this.manualDialog.selected || this.manualDialog.selected.length === 0) {
        this.$modal.msgError('请选择要配货的明细');
        return;
      }
      this.$confirm('确定对选中的明细进行手工配货吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.loading = true;
        // 实际应传主单id和明细id数组
        // 这里使用模拟API，实际项目中应替换为正确的API
        Promise.resolve()
          .then(() => {
            this.$modal.msgSuccess('手工配货成功');
            this.getList();
            this.closeManualDialog();
          })
          .catch(() => {
            this.$modal.msgError('手工配货失败');
          })
          .finally(() => {
            this.loading = false;
          });
      });
    },
    /** 主表格 Checkbox 事件 */
    mainCheckboxChange({ records }) {
      this.ids = records.map(item => item.id);
    },
    mainCheckboxAll({ records }) {
      this.ids = records.map(item => item.id);
    },
    /** 单元格点击事件 */
    cellClickEvent({ row }) {
      if (row && row.id !== this.currentCellId) {
        this.currentCellId = row.id;
      }
    },
    handleBatchCommand(type) {
      if (this.ids.length === 0) {
        this.$modal.msgError("请选择数据");
        return;
      }
      if (type === 'antiAudit') {
        this.$confirm('确定要对选中的配货单进行反审核吗？', '提示', {
          type: 'warning'
        }).then(() => {
          this.loading = true;
          // 这里使用模拟API，实际项目中应替换为正确的API
          Promise.resolve({ orderIds: this.ids })
            .then(() => {
              this.$modal.msgSuccess('反审核成功');
              this.getList();
            })
            .catch(() => {
              this.$modal.msgError('反审核失败');
            })
            .finally(() => {
              this.loading = false;
            });
        });
        return;
      }
      this.batchDialog.type = type;
      this.batchDialog.visible = true;
      // 清空表单
      this.batchForm = { warehouseName: '', expressCompany: '' };
    },

    handleBatchSubmit() {
      if (this.batchDialog.type === 'warehouse') {
        if (!this.batchForm.warehouseName) {
          this.$modal.msgError('请输入新仓库名称');
          return;
        }
        const params = {
          warehouseName: this.batchForm.warehouseName,
          orderIds: this.ids
        };
        this.loading = true;
        // 这里使用模拟API，实际项目中应替换为正确的API
        Promise.resolve()
          .then(() => {
            this.$modal.msgSuccess('批量修改仓库成功');
            this.batchDialog.visible = false;
            this.getList();
          })
          .catch(() => {
            this.$modal.msgError('批量修改仓库失败');
          })
          .finally(() => {
            this.loading = false;
          });
        return;
      }
      if (this.batchDialog.type === 'express') {
        if (!this.batchForm.expressCompany) {
          this.$modal.msgError('请输入新物流公司');
          return;
        }
        const params = {
          expressCompany: this.batchForm.expressCompany,
          orderIds: this.ids
        };
        this.loading = true;
        // 这里使用模拟API，实际项目中应替换为正确的API
        Promise.resolve()
          .then(() => {
            this.$modal.msgSuccess('批量修改物流公司成功');
            this.batchDialog.visible = false;
            this.getList();
          })
          .catch(() => {
            this.$modal.msgError('批量修改物流公司失败');
          })
          .finally(() => {
            this.loading = false;
          });
        return;
      }
      if (this.batchDialog.type === 'stock') {
        const params = {
          orderIds: this.ids,
          inStock: true
        };
        this.loading = true;
        // 这里使用模拟API，实际项目中应替换为正确的API
        Promise.resolve()
          .then(() => {
            this.$modal.msgSuccess('批量转为现货订单成功');
            this.batchDialog.visible = false;
            this.getList();
          })
          .catch(() => {
            this.$modal.msgError('批量转为现货订单失败');
          })
          .finally(() => {
            this.loading = false;
          });
        return;
      }
    },
    handleBatchCancel() {
      this.batchDialog.visible = false;
    },
    // 添加缺失的方法
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
      };
      this.cancelled = false;
      this.intercepted = false;
      this.payTime = this.getDefaultDateRange();
      this.handleQuery();
    },
    closeSplitDialog() {
      this.splitDialog.visible = false;
      this.splitDialog.data = null;
      this.splitDialog.splitQty = 1;
    },
    handleSplitSubmit() {
      if (!this.splitDialog.splitQty || this.splitDialog.splitQty < 1) {
        this.$modal.msgError("请输入有效的拆分数量");
        return;
      }
      // 调用拆分API
      this.$modal.msgSuccess("拆分成功");
      this.closeSplitDialog();
      this.getList();
    },
    closeManualDialog() {
      this.manualDialog.visible = false;
      this.manualDialog.detailList = [];
      this.manualDialog.selected = [];
    },
    onManualCheckChange({ checked, row }) {
      if (checked) {
        if (!this.manualDialog.selected.includes(row.id)) {
          this.manualDialog.selected.push(row.id);
        }
      } else {
        const index = this.manualDialog.selected.indexOf(row.id);
        if (index > -1) {
          this.manualDialog.selected.splice(index, 1);
        }
      }
    }
  }
};
</script>

<style lang="scss" scoped>
  .app-container{
    &-main{
      min-height: 400px;
    }
    &-footer{
      margin-top: 20px;
      &-title{
        display: flex;
        margin-bottom: 20px;
        &-item{
          cursor: pointer;
          padding: 5px 20px;
          border-radius: 8px;
        }
        .active{
          background-color: aqua;
        }
      }
    }
  }
.app-container-footer {
  margin-top: 20px;
}

.mb8 {
  margin-bottom: 8px;
}
</style>
